package com.mp.approvalreq.util;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class DateUtils {

	public static SimpleDateFormat getSimpleDateFormat(String pattern) {
        return new SimpleDateFormat(pattern);
    }


    private static final Map<String, ThreadLocal<SimpleDateFormat>> sdfMap = new HashMap<>();

    private static final Object lock = new Object();

    /**
     *  每个线程只会有一个SimpleDateFormat
     *  注意:不要在多线程单实例的servlet下使用,因为该线程只存在一个SimpleDateFormat,可以使用下面那个
     */
    public static SimpleDateFormat getSingleSDF(final String pattern) {
        ThreadLocal<SimpleDateFormat> tl = sdfMap.get(pattern);
        if (tl == null) {
            tl = sdfMap.get(pattern);
            synchronized (lock) {
                if (tl == null) {
                    tl = ThreadLocal.withInitial(() -> new SimpleDateFormat(pattern));
                    sdfMap.put(pattern, tl);
                }
            }
        }
        return tl.get();
    }


    public static final String YMDHMS   = "yyyy-MM-dd HH:mm:ss";
    public static final String YMDHM    = "yyyy-MM-dd HH:mm";
    public static final String YMD      = "yyyy-MM-dd";
    private static final String YM       = "yyyy-MM";
	private static final String CH_YMDHM = "yyyy-MM-dd E HH:mm";
	public static final int LEAVE_LIMITED = 200;


    private static final ThreadLocal<Map<String, SimpleDateFormat>> mapThreadLocal = new ThreadLocal<>();

    private static SimpleDateFormat createSDF(final String pattern) {
        if (pattern.equals(CH_YMDHM)) {
            return new SimpleDateFormat(pattern, Locale.CHINESE);
        }
        return new SimpleDateFormat(pattern);
    }

    /**
     *   每个线程都可以有多个SimpleDateFormat
     */
    public static SimpleDateFormat getSdf(final String pattern) {
        Map<String, SimpleDateFormat> sdfMap = mapThreadLocal.get();
        if (sdfMap == null) {
            sdfMap = new HashMap<>();
            sdfMap.put(pattern, createSDF(pattern));
            mapThreadLocal.set(sdfMap);
        } else {
            sdfMap.put(pattern, createSDF(pattern));
        }
        return sdfMap.get(pattern);
    }
	
	
	/**
	 *  计算两个毫秒数相差多少天,不满一天算0天
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static long countDays(long date1, long date2) {
		return Math.abs(date1 - date2) / (1000 * 60 * 60 * 24);
	}
	
	
	public static void main(String[] args) {
		System.out.println(getCurrentMonth());
		SimpleDateFormat sdf = DateUtils.getSimpleDateFormat(DateUtils.YM);
		System.out.println(sdf.format(System.currentTimeMillis()));
	}


	public static String getCurrentMonth() {
		SimpleDateFormat sdf = DateUtils.getSimpleDateFormat(DateUtils.YM);
		return sdf.format(System.currentTimeMillis());
	}
	
}
